package queue;

//基于链表实现队列
public class MyQueue {
    static class Node{
        private String val;
        private Node next = null;

        public Node(String val) {
            this.val = val;
        }
    }

    private Node head = null;   //队头
    private Node tail = null;   //队尾
    //入队
    public void offer(String val){
        Node newNode = new Node(val);
        //注意是否是空队列
        if(head == null){
            head = newNode;
            tail = newNode;
        }else{  //非空队列进行尾插
            tail.next = newNode;
            tail = newNode;
        }
    }
    //出队
    public String poll(){
        //空队列，返回null
        if(head == null){
            return null;
        }
        //注意是否是只有一个元素的队列
        String ret = head.val;
        if(head == tail){
            head = null;
            tail = null;
        }else{
            head = head.next;
        }

        return ret;
    }
    //获取队首元素
    public String peek(){
        //空队列，返回null
        if(head == null){
            return null;
        }
        return head.val;
    }
    //判空
    public boolean isEmpty(){
//        if(head == null){
//            return true;
//        }
//        return false;
        return head == null;
    }
    //求队列大小
    public int size(){
        int sz = 0;
        for(Node cur = head; cur != null; cur = cur.next){
            sz++;
        }
        return sz;
    }

    public static void main(String[] args) {
        MyQueue queue = new MyQueue();
        System.out.println(queue.isEmpty());
        queue.offer("a");
        queue.offer("b");
        queue.offer("x");
        queue.offer("g");

        System.out.println(queue.size());
        System.out.println(queue.isEmpty());
        System.out.println(queue.peek());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
    }
}
